package com.wangdao.wechatmall.service.wx;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangdao.wechatmall.bean.bo.wx.GoodsListBO;
import com.wangdao.wechatmall.bean.pojo.*;
import com.wangdao.wechatmall.bean.vo.admin.GoodsDetailVO;
import com.wangdao.wechatmall.bean.vo.wx.GoodsCategoryVO;
import com.wangdao.wechatmall.bean.vo.wx.GoodsListVO;
import com.wangdao.wechatmall.bean.vo.wx.GoodsRelatedVO;
import com.wangdao.wechatmall.bean.vo.wx.WXGoodsDetailVO;
import com.wangdao.wechatmall.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: JK
 * @Date: create in 2021/7/11 20:02
 */
@Service
public class WXGoodsServiceImpl implements WXGoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;

    @Autowired
    GrouponRulesMapper grouponRulesMapper;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    CollectMapper collectMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    FootprintMapper footprintMapper;

    @Override
    public long queryGoodsNumber() {
        GoodsExample goodsExample = new GoodsExample();
        long goodsNumber = goodsMapper.countByExample(goodsExample);
        return goodsNumber;
    }

    @Override
    public GoodsCategoryVO queryCategory(Integer id) {
        // 根据id查询当前目录
        Category category = categoryMapper.selectByPrimaryKey(id);

        GoodsCategoryVO goodsCategoryVO = new GoodsCategoryVO();

        // 判断当前目录是一级目录还是二级目录
        if (category.getPid() == 0) {
            // 当前目录是一级目录
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
            categoryExampleCriteria.andPidEqualTo(id);
            categoryExampleCriteria.andDeletedEqualTo(0);
            // 查询一级目录下的二级目录
            List<Category> brotherCategory = categoryMapper.selectByExample(categoryExample);
            if (brotherCategory.size() > 0) {
                // 二级目录不空
                goodsCategoryVO.setParentCategory(category);
                goodsCategoryVO.setCurrentCategory(brotherCategory.get(0));
                goodsCategoryVO.setBrotherCategory(brotherCategory);
            } else {
                // 二级目录为空
                goodsCategoryVO.setParentCategory(category);
                goodsCategoryVO.setCurrentCategory(category);
                goodsCategoryVO.setBrotherCategory(brotherCategory);
            }

        } else {
            // 当前目录是二级目录
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
            categoryExampleCriteria.andPidEqualTo(category.getPid());
            categoryExampleCriteria.andDeletedEqualTo(0);
            List<Category> brotherCategory = categoryMapper.selectByExample(categoryExample);
            Category parentCategory = categoryMapper.selectByPrimaryKey(category.getPid());
            goodsCategoryVO.setParentCategory(parentCategory);
            goodsCategoryVO.setCurrentCategory(category);
            goodsCategoryVO.setBrotherCategory(brotherCategory);
        }

        return goodsCategoryVO;
    }

    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    @Override
    public GoodsListVO queryGoodsList(GoodsListBO goodsListBO) {

        /*---------------code by shuiYi--------------*/
        if (goodsListBO.getKeyword() != null) {
            addHistory(goodsListBO);
        }


        /*--------------------------------------------*/
        // 设置分页查询
        PageHelper.startPage(goodsListBO.getPage(), goodsListBO.getSize());

        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        if (!StringUtils.isEmpty(goodsListBO.getCategoryId()) && goodsListBO.getCategoryId() != 0) {
            goodsExampleCriteria.andCategoryIdEqualTo(goodsListBO.getCategoryId());
        }
        if (!StringUtils.isEmpty(goodsListBO.getBrandId())) {
            goodsExampleCriteria.andBrandIdEqualTo(goodsListBO.getBrandId());
        }
        if (!StringUtils.isEmpty(goodsListBO.getKeyword())) {
            goodsExampleCriteria.andNameLike("%" + goodsListBO.getKeyword() + "%");
        }
        if (!StringUtils.isEmpty(goodsListBO.getSort()) && !StringUtils.isEmpty(goodsListBO.getOrder())) {
            goodsExample.setOrderByClause(goodsListBO.getSort() + " " + goodsListBO.getOrder());
        }

        goodsExampleCriteria.andDeletedEqualTo(false);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        ArrayList<GoodsListVO.GoodsListDTO> goodsListDTOS = new ArrayList<>();
        // 将Goods转换为
        for (Goods good : goods) {
            GoodsListVO.GoodsListDTO goodsListDTO = new GoodsListVO.GoodsListDTO(good.getId(), good.getName(), good.getBrief(), good.getPicUrl(), good.getIsNew(), good.getIsHot(), good.getCounterPrice(), good.getRetailPrice());
            goodsListDTOS.add(goodsListDTO);
        }

        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);
        int count = goodsPageInfo.getSize();

        // 查询filterCategoryList
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
        categoryExampleCriteria.andLevelEqualTo("L2");
        categoryExampleCriteria.andDeletedEqualTo(0);
        List<Category> filterCategoryList = categoryMapper.selectByExample(categoryExample);

        GoodsListVO goodsListVO = new GoodsListVO();
        goodsListVO.setGoodsList(goodsListDTOS);
        goodsListVO.setCount(count);
        goodsListVO.setFilterCategoryList(filterCategoryList);
        return goodsListVO;
    }

    private void addHistory(GoodsListBO goodsListBO) {
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
        criteria.andUserIdEqualTo(1);    // todo
        boolean flag = false;
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        for (SearchHistory searchHistory : searchHistories) {
            if (searchHistory.getKeyword().equals(goodsListBO.getKeyword())) {
                SearchHistory searchHistory1 = new SearchHistory();
                searchHistory1.setDeleted(false);
                Date date = new Date();
                searchHistory1.setUpdateTime(date);
                searchHistory1.setId(searchHistory.getId());
                searchHistoryMapper.updateByPrimaryKeySelective(searchHistory1);
                flag = true;
                break;
            }
        }
        if (!flag) {
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setKeyword(goodsListBO.getKeyword());
            searchHistory.setDeleted(false);
            searchHistory.setUpdateTime(new Date());
            searchHistory.setAddTime(new Date());
            searchHistory.setUserId(1);
            searchHistoryMapper.insertSelective(searchHistory);
        }
    }

    @Override
    public WXGoodsDetailVO queryGoodsDetail(Integer goodsId) {
        Subject subject = SecurityUtils.getSubject();
        Date currentDate = new Date();

        // 1.根据goodsId查询商品信息
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);

        // 2.根据goodsId查询specificationList
        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        GoodsSpecificationExample.Criteria goodsSpecificationExampleCriteria = goodsSpecificationExample.createCriteria();
        goodsSpecificationExampleCriteria.andGoodsIdEqualTo(goodsId);
        goodsSpecificationExampleCriteria.andDeletedEqualTo(false);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        ArrayList<String> goodsSpecificationNames = new ArrayList<>();
        for (GoodsSpecification goodsSpecification : goodsSpecifications) {
            if (!goodsSpecificationNames.contains(goodsSpecification.getSpecification())) {
                goodsSpecificationNames.add(goodsSpecification.getSpecification());
            }
        }
        ArrayList<WXGoodsDetailVO.SpecificationListDTO> specificationListDTOS = new ArrayList<>();
        for (int i = 0; i < goodsSpecificationNames.size(); i++) {
            // 获取当前商品规格名
            String currentSpecificationName = goodsSpecificationNames.get(i);

            WXGoodsDetailVO.SpecificationListDTO specificationListDTO = new WXGoodsDetailVO.SpecificationListDTO();
            ArrayList<GoodsSpecification> valueList = new ArrayList<>();
            for (GoodsSpecification goodsSpecification : goodsSpecifications) {
                if (currentSpecificationName.equals(goodsSpecification.getSpecification())) {
                    valueList.add(goodsSpecification);
                }
            }
            specificationListDTO.setName(currentSpecificationName);
            specificationListDTO.setValueList(valueList);
            specificationListDTOS.add(specificationListDTO);
        }

        // 3.根据goodsId查询group_rules
        GrouponRulesExample grouponRulesExample = new GrouponRulesExample();
        GrouponRulesExample.Criteria grouponRulesExampleCriteria = grouponRulesExample.createCriteria();
        grouponRulesExampleCriteria.andGoodsIdEqualTo(goodsId);
        grouponRulesExampleCriteria.andDeletedEqualTo(false);
        List<GrouponRules> grouponRules = grouponRulesMapper.selectByExample(grouponRulesExample);

        // 4.查询所有的issue
        IssueExample issueExample = new IssueExample();
        IssueExample.Criteria issueExampleCriteria = issueExample.createCriteria();
        issueExampleCriteria.andDeletedEqualTo(0);
        issueMapper.selectByExample(issueExample);

        // 5.shareImage，暂时不用写

        // 6.根据goodsId(对应comment表中的valueId)查询comment，根据userId查询user，即可知道nickname和avatar
        PageHelper.offsetPage(0, 2);
        CommentExample commentExample = new CommentExample();
        CommentExample.Criteria commentExampleCriteria = commentExample.createCriteria();
        commentExampleCriteria.andValueIdEqualTo(goodsId);
        commentExampleCriteria.andDeletedEqualTo(false);
        commentExample.setOrderByClause("add_time desc");
        List<Comment> comments = commentMapper.selectByExample(commentExample);

        WXGoodsDetailVO.CommentDTO commentDTO = new WXGoodsDetailVO.CommentDTO();
        ArrayList<WXGoodsDetailVO.CommentDTO.DataDTO> dataDTOS = new ArrayList<>();
        for (Comment comment : comments) {
            User user = userMapper.selectByPrimaryKey(comment.getUserId());
            WXGoodsDetailVO.CommentDTO.DataDTO dataDTO = new WXGoodsDetailVO.CommentDTO.DataDTO(comment.getAddTime(), comment.getPicUrls(), user.getNickname(), comment.getId(), user.getAvatar(), comment.getContent());
            dataDTOS.add(dataDTO);
        }
        PageInfo<Comment> commentPageInfo = new PageInfo<>(comments);
        commentDTO.setCount(commentPageInfo.getTotal());
        commentDTO.setData(dataDTOS);

        // 7.根据goodsId查询goods_attribute
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        GoodsAttributeExample.Criteria goodsAttributeExampleCriteria = goodsAttributeExample.createCriteria();
        goodsAttributeExampleCriteria.andGoodsIdEqualTo(goodsId);
        goodsAttributeExampleCriteria.andDeletedEqualTo(false);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        // 8.根据brandId查询brand
        Brand brand = brandMapper.selectByPrimaryKey(goods.getBrandId());

        // 9.根据goodsId查询goods_product
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria goodsProductExampleCriteria = goodsProductExample.createCriteria();
        goodsProductExampleCriteria.andGoodsIdEqualTo(goodsId);
        goodsProductExampleCriteria.andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);

        // TODO userHasCollect、footprint需要使用到user信息
        // 10.userHasCollect，用户是否收藏
        // 11.footprint，添加历史足迹
        // 先从session中取出username
        // 如果username=null，用户没有登录，userHasCollect=0
        // 如果username!=null，根据username查询user的userId，根据userId和goodsId查询collect表，就可以知道userHasCollect的值了
        int userHasCollect = 0;
        if (subject.getPrincipals() != null && subject.getPrincipals().getPrimaryPrincipal() != null) {
            // userHasCollect
            String username = ((String) subject.getPrincipals().getPrimaryPrincipal());
            UserExample userExample = new UserExample();
            UserExample.Criteria userExampleCriteria = userExample.createCriteria();
            userExampleCriteria.andUsernameEqualTo(username);
            userExampleCriteria.andDeletedEqualTo(false);
            List<User> users = userMapper.selectByExample(userExample);
            User user = users.get(0);
            Integer userId = user.getId();
            CollectExample collectExample = new CollectExample();
            CollectExample.Criteria collectExampleCriteria = collectExample.createCriteria();
            collectExampleCriteria.andUserIdEqualTo(userId);
            collectExampleCriteria.andValueIdEqualTo(goodsId);
            collectExampleCriteria.andDeletedEqualTo(false);
            List<Collect> collects = collectMapper.selectByExample(collectExample);
            if (collects.size() > 0) {
                userHasCollect = 1;
            }

            // 添加footprint
            Footprint footprint = new Footprint(null, userId, goodsId, currentDate, currentDate, false);
            footprintMapper.insertSelective(footprint);
        }

        WXGoodsDetailVO wxGoodsDetailVO = new WXGoodsDetailVO();
        wxGoodsDetailVO.setInfo(goods);
        wxGoodsDetailVO.setSpecificationList(specificationListDTOS);
        wxGoodsDetailVO.setGroupon(grouponRules);
        wxGoodsDetailVO.setUserHasCollect(userHasCollect);
        wxGoodsDetailVO.setShareImage(null);
        wxGoodsDetailVO.setComment(commentDTO);
        wxGoodsDetailVO.setAttribute(goodsAttributes);
        wxGoodsDetailVO.setBrand(brand);
        wxGoodsDetailVO.setProductList(goodsProducts);

        return wxGoodsDetailVO;
    }

    @Override
    public List<GoodsRelatedVO> queryGoodsRelated(Integer id) {
        // 1.先根据商品id查询到商品
        Goods goods = goodsMapper.selectByPrimaryKey(id);

        // 2.根据商品的categoryId，查询该category下的所有商品，即相关联的商品
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        goodsExampleCriteria.andCategoryIdEqualTo(goods.getCategoryId());
        goodsExampleCriteria.andDeletedEqualTo(false);
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);

        // 将Goods转换为GoodsRelatedVO
        ArrayList<GoodsRelatedVO> goodsRelatedVOS = new ArrayList<>();
        for (Goods goodsRelated : goodsList) {
            GoodsRelatedVO goodsRelatedVO = new GoodsRelatedVO(goodsRelated.getId(), goodsRelated.getName(), goodsRelated.getBrief(), goodsRelated.getPicUrl(), goodsRelated.getIsNew(), goodsRelated.getIsHot(), goodsRelated.getCounterPrice(), goodsRelated.getRetailPrice());
            goodsRelatedVOS.add(goodsRelatedVO);
        }

        return goodsRelatedVOS;
    }
}
